import { apiUrl } from '@/config/env';
import {store} from '@/core/store'

import axios from "axios"
export default url => {
  const crud = window.$crud(url)

  const merge = (formData) => window.$axios({
    url: `${url}/merge`,
    method: 'post',
    data:formData
  })

  const getList = (folderId) => window.$axios({
    url: `${url}/${folderId}/list`,
    method: 'get'
  })

  const remove = (fileId) => window.$axios({
      url: `${url}/${fileId}`,
      method: 'delete'
  })
  const removeChunks = (fileId,chunks) => window.$axios({
      url: `${url}/${fileId}/${chunks}`,
      method: 'delete'
  })

  const uploadTemp = (ioc,data) => window.$axios({
      url: `${url}/import/temp/${ioc}`,
      method: 'post',
      data
  })

  const download = (fileId, fileName) => axios.create()
    .get(`${apiUrl}${url}/download/${fileId}?token=${store.getters.token}`, { responseType: 'blob'})
    .then(response => {
      // 提取文件名
      // const fileName = response.headers['content-disposition'].match(
      //   /filename=(.*)/
      // )[1]

      // 创建新的URL并指向File对象或者Blob对象的地址
      const blobURL = window.URL.createObjectURL(response.data)
      // 创建a标签，用于跳转至下载链接
      const tempLink = document.createElement('a')
      tempLink.style.display = 'none'
      tempLink.href = blobURL
      tempLink.setAttribute('download', fileName)
      // 兼容：某些浏览器不支持HTML5的download属性
      if (typeof tempLink.download === 'undefined') {
        tempLink.setAttribute('target', '_blank')
      }
      // 挂载a标签
      document.body.appendChild(tempLink)
      tempLink.click()
      document.body.removeChild(tempLink)
      // 释放blob URL地址
      window.URL.revokeObjectURL(blobURL)
    })

  const getHtml = (fileId) => window.$axios({
      url: `${url}/html/${fileId}`,
      method: 'get'
  })

  return {
    ...crud,
    merge,
    remove,
    getList,
    removeChunks,
    uploadTemp,
    getHtml,
    download
  }
}